﻿using LetsTestAPI.EDM;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace LetsTestAPI.Controllers
{
    public class MSLANGUAGESController : ApiController
    {
        public IEnumerable<string> GetListOfLanguages()
        {
            using (LetsTestEntities context = new LetsTestEntities())
            {
                return context.Languages.Where(t => t.IsActive == true).Select(t => t.Name).ToArray();
            }
        }


        [HttpPost]
        public void AddOrEditLanguage([FromBody]JObject jsonData)
        {
            string Name = String.Empty;
            int LanguageID = 0;
            string IsActive = String.Empty;
            if (jsonData["Name"] != null) { Name = jsonData["Name"].ToString(); }
            if (jsonData["LanguageID"] != null) LanguageID = Int32.Parse(jsonData["LanguageID"].ToString());
            if (jsonData["IsActive"] != null) IsActive = jsonData["IsActive"].ToString();

            using (LetsTestEntities context = new LetsTestEntities())
            {
                if (LanguageID != 0)
                {
                    var rows = context.Languages.Where(t => t.Id == LanguageID);
                    if (rows != null)
                    {
                        var row = rows.FirstOrDefault();
                        if (!String.IsNullOrEmpty(Name)) row.Name = Name;
                        if (!String.IsNullOrEmpty(IsActive)) row.IsActive = Boolean.Parse(IsActive);
                        context.SaveChanges();
                    }


                }
                else
                {
                    context.Languages.Add(new Language { Name = Name, IsActive = true });
                    context.SaveChanges();
                }
            }


        }
    }
}
